<?php
/**
 * Created by PhpStorm.
 * User: lili
 * Date: 2018/12/29
 * Time: 13:08
 */

namespace app\admin\controller;


use app\admin\model\Check;
use app\admin\model\Export;
use app\admin\model\User;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\Controller;

class Data extends Controller
{


    protected $beforeActionList = [
        'first'  =>  ['only'=>'index'],


    ];

    protected function first()
    {
        $this->assign('t',8);

    }


    public function index(){
        return $this->fetch();
    }

   


    public function listjson(){

        $export = new Export();
        $send = input();
        $where = array();
        
        $page = empty($send['page'])?1:$send['page'];
        $limit = empty($send['limit'])?10:$send['limit'];
        // $users = collection($user->getAllUser($page,$limit))->toArray();
        $res = $export->where($where)->page($page,$limit)->order('id desc')->select();
        foreach ($res as &$v){
            switch ($v['status']){
                case 1 : $v['status'] = '正在生成';break;
                case 2 : $v['status'] = '生成成功';break;
                default:$v['status'] = '正在生成';
            }
        }
        $count = $export->count();
        $resjson = '{ "code": 0, "msg": "","count": '.$count.', "data":'.json_encode($res) .'}';
        echo $resjson;
    }
    
    
    
    
    
    
    
    /*
     * 异步执行
     *
     *
     * */
    public function asynchronous(){
        $send = input();
        $request = request();
        $ch = curl_init();
        // set url
        curl_setopt($ch, CURLOPT_URL,   $request->domain().url('Data/getPatExcel'));
//        dump($request->domain());
        $data = $send;
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不验证证书下同
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $rawdata = curl_exec($ch);

        curl_close($ch);

    }



    /*
     * 多个用户批量导出
     *
     *
     * */
    public function getPatExcel(){

        set_time_limit(0);
        ini_set ('memory_limit', '1024M')  ;

        $send = input();
        if(!empty($send['uids'])){
            $uids = explode(',',$send['uids'] );
        }else{
            $usermodel = new User();
            $uids=$usermodel->field('uid')->select();
            $uids =  array_column(collection($uids)->toArray(), 'uid') ;

//            dump($uids);
        }
//        var_dump($send);
		$start_time = $send['start_time'];
        $end_time = $send['end_time'];
        $dataarr = array();
        $moban = str_replace('\\','/' , ROOT_PATH.'public/static/excel/V1.xlsx');
        if (file_exists($moban)){
            $spreadsheet = IOFactory::load(ROOT_PATH.'public/static/excel/V1.xlsx');
            $worksheet = $spreadsheet->getActiveSheet();
//            $spreadsheet = new Spreadsheet();

            //录入数据库
            $relativepath = '/static/excel/export/'.date('YmdHis').'.xls';
            $file = ROOT_PATH.'public'.$relativepath;
            //通过php保存在本地的时候需要用到
            $exportmodel = new Export();
            $path = $file;
            $path = iconv("UTF-8", "GB2312//IGNORE", $file);
            $path = $path = str_replace('\\', '/', $path);
            $data = array(
                'filename'  => substr($path,strlen(dirname($path))+1 ),
                'filepath'  => $relativepath,
                'status'    => 1
            );
            $exportmodel->isUpdate(false)->save($data);
            
            
            foreach ($uids as $uid){
                $checkmodel = new Check();
                $usermodel = new User();
                $user = $usermodel->getUserByuid($uid);
//            dump($user->toArray());
                //if (empty($user)){
					
                //    $this->error('没有该用户');
                //}
                $create_time = $user['create_time'];

                if(!empty($start_time)){
                    $sdatetime = strtotime($start_time);
                }else{
                    $sdatetime = strtotime($create_time);//开始时间
                    $sdatetime =  strtotime(date('Y-m-d',$sdatetime)) ;//0点时间戳
                }

                if(!empty($end_time)){
                    $edatetime = strtotime($end_time);
                }else{
                    $edatetime = time();//结束时间
                    $edatetime =  strtotime(date('Y-m-d',$edatetime)) ;//0点时间戳
                }

                while ($sdatetime<=$edatetime){
                    $data = $checkmodel->getDataExport($uid,$sdatetime);//获取一个用户一个时间的数据
                    $dataarr[] = $data;
                    $sdatetime = strtotime('+1day',$sdatetime);//时间戳+1day

                }
            }












            $styleArray = [
                'alignment' => [
                    'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
                ],
                'borders' => [
                    'outline' => [
                        'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
                        'color' => ['argb' => '000000'],
                    ],
                ],
            ];







            foreach ($dataarr as $item => $value){
                $worksheet->setCellValue('A'.($item+4),$item+1 );
                $worksheet->getStyle('A'.($item+4))->applyFromArray($styleArray);
                foreach ($value as $item2 => $value2){
                    $worksheet->setCellValue($item2.''.($item+4),$value2===null?'-':$value2 );
                    $worksheet->getStyle($item2.''.($item+4))->applyFromArray($styleArray);
                }
            }

			
            $this->downloadExcel($spreadsheet,$file,'xls',$exportmodel);
        }else{
            $this->error('模板缺失');
        }
    }




    /*
     * 导出Excel
     *
     *
     *
     * */
    public function getExcel(){
        $send = input();
        if (empty($send['uid'])){
            $this->error('uid缺失');
        }
        $uid = $send['uid'];
        $dataarr = array();
        $moban = str_replace('\\','/' , ROOT_PATH.'public/static/excel/V1.xlsx');
//        echo $moban;
        if (file_exists($moban)){
            $spreadsheet = IOFactory::load(ROOT_PATH.'public/static/excel/V1.xlsx');
            $worksheet = $spreadsheet->getActiveSheet();
//            $spreadsheet = new Spreadsheet();


            $checkmodel = new Check();
            $usermodel = new User();
            $user = $usermodel->getUserByuid($uid);
//            dump($user->toArray());
            if (empty($user)){
                $this->error('没有该用户');
            }
            $create_time = $user['create_time'];

            $sdatetime = strtotime($create_time);//开始时间
            $sdatetime =  strtotime(date('Y-m-d',$sdatetime)) ;//0点时间戳

            $edatetime = time();//结束时间
            $edatetime =  strtotime(date('Y-m-d',$edatetime)) ;//0点时间戳
            while ($sdatetime<=$edatetime){
                 
                $data = $checkmodel->getDataExport($uid,$sdatetime);
                $dataarr[] = $data;
                $sdatetime = strtotime('+1day',$sdatetime);//时间戳+1day

            }
            $styleArray = [
                'alignment' => [
                    'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
                ],
                'borders' => [
                    'outline' => [
                        'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
                        'color' => ['argb' => '000000'],
                    ],
                ],
            ];
            foreach ($dataarr as $item => $value){
                $worksheet->setCellValue('A'.($item+4),$item+1 );
                $worksheet->getStyle('A'.($item+4))->applyFromArray($styleArray);
                foreach ($value as $item2 => $value2){
                    $worksheet->setCellValue($item2.''.($item+4),$value2===null?'-':$value2 );
                    $worksheet->getStyle($item2.''.($item+4))->applyFromArray($styleArray);
                }
            }


            $this->downloadExcel($spreadsheet,'dataexport','xls');
        }else{
            $this->error('模板缺失');
        }




    }









    //公共文件，用来传入xls并下载
    protected function downloadExcel($newExcel, $file, $format,$exportmodel='')
    {
        $format = strtolower($format);


        // $format只能为 Xlsx 或 Xls
       /* if (  $format == 'xlsx') {
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            echo 1;
        } elseif ($format == 'xls') {
            header('Content-Type: application/vnd.ms-excel');
        }*/

//        header("Content-Disposition: attachment;filename=" . $filename . date('Y-m-d:H:i') . '.' . strtolower($format));
        header('Cache-Control: max-age=0');
        $objWriter = new Xlsx($newExcel);

//        $objWriter->save('php://output');
        if(!is_dir(ROOT_PATH.'public/static/excel/export/')){
            mkdir(ROOT_PATH.'public/static/excel/export/',0777,true);
        }
        $relativepath = '/static/excel/export/'.date('YmdHis').'.xls';
         
        //通过php保存在本地的时候需要用到
//        $exportmodel = new Export();
       


        $objWriter->save($file);


        while (1){
            if(file_exists($file)){
                $exportmodel->save(array('status'=>2));
                sleep(1);
                break;
            }

        }

        //以下为需要用到IE时候设置
        // If you're serving to IE 9, then the following may be needed
        //header('Cache-Control: max-age=1');
        // If you're serving to IE over SSL, then the following may be needed
        //header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        //header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        //header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        //header('Pragma: public'); // HTTP/1.0
        exit;
    }

    /*
     * 删除导出的数据
     *
     *
     * */
    public function delete(){
        $send = input();
        $uid = $send['uid'];
        $exportmodel = new Export();
        $res = $exportmodel->find($uid);
        $filepath =  ROOT_PATH."public/". substr($res['filepath'],1 ) ;
        $filepath = str_replace('\\','/' ,$filepath );
        //http://www.dazhihui2188.com/admin.php/data/delete.html?uid=69
        if (file_exists($filepath)){

            unlink($filepath);
        }
        $d = $exportmodel->destroy($uid);

        if ($d){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }

    }
    
    
    
    
    
}